package com.dhecp.project.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.core.utils.dingtalk.DingTalkUtils;
import com.dhecp.core.utils.dingtalk.DtApiUrls;
import com.dhecp.core.utils.dingtalk.DtHttpUtils;
import com.dhecp.project.common.controller.BaseModuleController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.*;

/**
 * @ClassName DingTalkController
 * @Description TODO
 * @Author alula
 * @Date 2022-03-07 15:21
 */
@Controller
@RequestMapping("/system/dingtalk")
public class DingTalkController extends BaseModuleController {

    /**  获取所有部门
     * @return AjaxResult
     */
    @RequestMapping("/deptlist")
    @ResponseBody
    public AjaxResult queryDeptList() {
        String token = DingTalkUtils.getToken(DingTalkUtils.H5APPKEY, DingTalkUtils.H5APPSECERT, DingTalkUtils.H5CACHEKEY);
        String requestUrl = DtApiUrls.DEPT_GET_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = DtHttpUtils.sendGet(requestUrl);
        if(jsonObject.get("errcode").toString().equals("0")) {
            return AjaxResult.success(jsonObject.get("result"));
        }else return AjaxResult.success(jsonObject);
    }

    /**  获取所有成员
     * @return AjaxResult
     */
    @RequestMapping("/userlist")
    @ResponseBody
    public AjaxResult queryUserList() {
        String token = DingTalkUtils.getToken(DingTalkUtils.H5APPKEY, DingTalkUtils.H5APPSECERT, DingTalkUtils.H5CACHEKEY);
        String requestUrl = DtApiUrls.DEPT_GET_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = DtHttpUtils.sendGet(requestUrl);
        if(jsonObject.get("errcode").toString().equals("0")) {
            new ArrayList<>();
            List<Object> allDeptList = JSONArray.parseArray(jsonObject.get("result").toString(), Object.class);
            allDeptList = queryAllDept(allDeptList, token);
            //获取根部门下用户
            List<Object> userList = queryAllUser(new ArrayList<Object>(), "1", token, "0");
            //获取子部门下用户
            for(Object jo : allDeptList) {
                userList = queryAllUser(userList, JSONObject.parseObject(JSONObject.toJSONString(jo), Map.class).get("dept_id").toString(), token, "0");
            }
            return AjaxResult.success(userList);
        }else return AjaxResult.success(jsonObject);
    }

    /**  递归获取所有部门（包括子部门）
     * @return AjaxResult
     */
    private List<Object> queryAllDept(List<Object> allDeptList, String token) {
        List<Object> newDept = new ArrayList<Object>();
        for(Object jo : allDeptList) {
            String requestUrl = DtApiUrls.SUB_DEPT_GET_URL.replace("ACCESS_TOKEN", token).replace("DEPT_ID", JSONObject.parseObject(JSONObject.toJSONString(jo), Map.class).get("dept_id").toString());
            JSONObject jsonObject = DtHttpUtils.sendGet(requestUrl);
            if(jsonObject.get("errcode").toString().equals("0")) {
                List<Object> deptList = JSONArray.parseArray(jsonObject.get("result").toString(), Object.class);
                newDept.addAll(deptList);
                if(deptList.size() > 0) {
                    newDept = queryAllDept(deptList, token);
                }
            }
        }
        allDeptList.addAll(newDept);
        return allDeptList;
    }

    /**  根据部门获取获取所有成员
     * @return AjaxResult
     */
    private List<Object> queryAllUser(List<Object> userList, String deptId, String token, String cursor) {
        String requestUrl = DtApiUrls.USER_GET_URL.replace("ACCESS_TOKEN", token).replace("DEPT_ID", deptId).replace("CURSOR", cursor).replace("SIZE","2");
        JSONObject jsonObject = DtHttpUtils.sendGet(requestUrl);
        if(jsonObject.get("errcode").toString().equals("0")) {
            JSONObject resultObj = (JSONObject)jsonObject.get("result");
            List<Object> userObj = JSONArray.parseArray(resultObj.get("list").toString(), Object.class);
            userList.addAll(userObj);
            if(resultObj.get("next_cursor") != null) {
                userList = queryAllUser(userList, deptId, token, resultObj.get("next_cursor").toString());
            }
        }
        return userList;
    }
}
